package middleware

import (
	"fmt"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取token
		token := c.Request.Header.Get("x-access-token")

		// 判断是否是非法token

		if token == "" {
			utils.FailWithMessage("非法访问", c)
			c.Abort()
			return
		}
		// 解析token
		j := tools.NewJWT()
		claims, err := j.ParseToken(token)
		if err != nil {
			if err == tools.TokenExpired {
				utils.MissLogin("授权已过期", c)
				c.Abort()
				return
			}
			utils.MissLogin(err.Error(), c)
			c.Abort()
			return
		}

		if claims.BaseClaims.Status == false {
			utils.FailWithMessage("该账号被禁用", c)
			c.Abort()
			return
		}

		// 刷新token
		if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
			// 根据登录的状态刷新账号
			var ep string
			if claims.UserType == "admin" {
				ep = global.OC_CONFIG.LoginTime.AdminEP
			} else if claims.UserType == "site" {
				ep = global.OC_CONFIG.LoginTime.SiteEP
				fmt.Println(global.OC_CONFIG.LoginTime.SiteEP)
				fmt.Println(ep)
			} else {
				ep = global.OC_CONFIG.LoginTime.NorEP
			}
			// 获取登录方式
			dr, _ := tools.ParseDuration(ep)
			claims.ExpiresAt = time.Now().Add(dr).Unix()
			newToken, _ := j.CreateTokenByOldToken(token, *claims)
			newClaims, _ := j.ParseToken(newToken)
			c.Header("new-token", newToken)
			c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt, 10))
		}

		c.Set("claims", claims)
		c.Next()
	}
}
